package m.store.task;

import m.common.action.Action;
import m.common.model.util.ModelUpdate;
import m.common.model.util.QueryCondition;
import m.store.model.GuestInfo;
import m.store.model.IncomeAmount;
import m.store.model.OrderModel;
import m.store.model.SaleInfo;
import m.system.db.TransactionManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

public class GuestSaleSupport implements Runnable {
    private GuestSaleSupport(){}
    private static boolean isRun=true;
    static Thread th;
    static final List<String> ls=new ArrayList<>();

    @Override
    public void run() {
        while (true){
            if(ls.isEmpty()){
                TransactionManager.closeConnection();
                LockSupport.park();
                TransactionManager.initConnection();
            }
            if(!isRun) break;
            if(!ls.isEmpty()){
                String oid=ls.remove(0);
                execute(oid);
            }
        }
    }
    private void execute(String oid){
        try {
            if(ls.size()<10) Thread.sleep(100L);
            //更新客户的出库金额
            ModelUpdate.init(GuestInfo.class)
            .set("saleAmount", SaleInfo.class, "ifnull(sum(round(#{saleAmount}-#{refundAmount},2)),0)",
                QueryCondition.and(
                    QueryCondition.eq("guest.oid", oid),
                    QueryCondition.eq("status", OrderModel.Status_Done)
                )
            )
            .set("saleIncomeAmount", IncomeAmount.class, "ifnull(sum(#{incomeAmount}),0)",
                QueryCondition.and(
                    QueryCondition.eq("guest.oid", oid),
                    QueryCondition.eq("status",OrderModel.Status_Done)
                )
            )
            .setExp("surplusAmount", "round(#{stockAmount}-#{stockPayAmount}-(#{saleAmount}-#{saleIncomeAmount}),2)")
            .execute(oid);
        } catch (Exception e) {
            Action.directLog("定时任务","更新客户出库金额失败",this.getClass().getName(),oid,e);
        }
    }
    /** 入库审核通过调用
     * 添加要更新客户oid
     */
    public static void add(String stock_oid){
        if(!ls.contains(stock_oid))
            ls.add(stock_oid);
    }

    /**
     * 开始更新
     */
    public static void start(){
        if(null==th){
            th=new Thread(new GuestSaleSupport());
            th.start();
        }else{
            LockSupport.unpark(th);
        }
    }

    public static void close(){
        isRun=false;
        LockSupport.unpark(th);
    }
}
